package server.app.fileupload;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import jodd.typeconverter.TypeConverterManager;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;

public enum FileDataFieldEnum
{
    NAME("name"), CONTENT_TYPE("contentType"), PATH("path"), MD5("md5"), SIZE("size"), UNKNOW("unknow");
    private String fieldName;

    FileDataFieldEnum(String fieldName)
    {
        this.fieldName = fieldName;
    }

    public static FileDataFieldEnum getFileDataField(String str)
    {
        String name = str;
        if (StringUtils.contains(str, "."))
        {
            name = StringUtils.substringAfter(str, ".");
        }
        for (FileDataFieldEnum field : values())
        {
            if (field.toString().equalsIgnoreCase(name))
            {
                return field;
            }
        }
        return UNKNOW;
    }

    static Map<Class, Map<String, Class>> beanMap = new HashMap<Class, Map<String, Class>>();

    public void invoke(Object object, Object value) throws IllegalAccessException, InvocationTargetException,
                    NoSuchMethodException
    {

        if (null == object || UNKNOW.equals(this))
        {
            throw new java.lang.RuntimeException("Unknow fileds");
        }

        Class clazz = object.getClass();
        if (!beanMap.containsKey(clazz))
        {
            beanMap.put(clazz, new HashMap<String, Class>());
        }

        Map<String, Class> classMap = beanMap.get(clazz);

        if (!classMap.containsKey(fieldName))
        {
            classMap.put(fieldName, PropertyUtils.getPropertyType(object, fieldName));
        }
        Class fieldClass = classMap.get(fieldName);

        if (null != value && fieldClass.isInstance(value))
        {
            PropertyUtils.setProperty(object, fieldName, value);
        }
        else if (null == value)
        {

            PropertyUtils.setProperty(object, fieldName, value);
        }
        else
        {
            PropertyUtils.setProperty(object, fieldName, TypeConverterManager.convertType(value, fieldClass));
        }
    }

}
